<?php
/**
 * Created by PhpStorm.
 * User: 87393
 * Date: 2019-03-27
 * Time: 12:00
 */

namespace App\Http\Repositories\Services\Impls;


use App\Exceptions\ServiceException;
use App\Http\Constants\CommonExceptionConstants;
use App\Http\Repositories\Daos\IRoleDao;
use App\Http\Repositories\Eloquent\Role;
use App\Http\Repositories\Services\IRole;
use App\Http\Requests\Admin\RoleInputDTO;
use App\Util\Helper;

class RoleService implements IRole
{

    protected $roleDao;

    public function __construct(IRoleDao $roleDao)
    {
        $this->roleDao = $roleDao;
    }

    public function map() {
        $data = $this->roleDao->all();
        return Helper::arrayMapByKey($data->toArray(), 'id', 'name');
    }


    public function store(RoleInputDTO $inputDTO)
    {
        $data = [];
        $data['name'] = $inputDTO->get('name');
        $data['display_name'] = $inputDTO->get('display_name');
        $data['guard_name'] = $inputDTO->get('guard_name');
        Role::create($data);
    }

    public function update(RoleInputDTO $inputDTO, $id)
    {
        $role = Role::findOrFail($id);
        if (!$role) {
            throw new ServiceException(CommonExceptionConstants::getKey('no_find_data'));
        }
        $data = [];
        $data['name'] = $inputDTO->get('name');
        $data['guard_name'] = $inputDTO->get('guard_name');
        $data['display_name'] = $inputDTO->get('display_name');
        $role->update($data);
    }

    public function byId($id)
    {
        $dao = $this->roleDao->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::getKey('no_find_data'));
        }
        return $dao;
    }

    public function lists($search, $page, $size)
    {
        $data = $this->roleDao->lists($search, $page, $size);
        return $data;
    }

    public function state($id, $state)
    {
        $where = ['id'=>['symbol'=>'in','val'=>explode(',',$id)]];
        $this->roleDao->update($where, ['state'=>$state]);
    }

    public function getAll()
    {
        $dao = $this->roleDao->byKey('is_deleted','=',0);
        return $dao;
    }

}